package com.lianyi.commonsdk.util.security;

import android.util.Log;

import java.util.Random;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


public class AESOperator {


    /*
     * 加密用的Key 可以用26个字母和数字组成 此处使用AES-128-CBC加密模式，key需要为16位。
     */
	public String sKey = "VyfQhURd6CrpnDI9";
	public String ivParameter = "tlBIcm4HU4xGO20H";
 
 
 
    
public String Encrypt(String encData , String secretKey, String vector) throws Exception {
        
        if(secretKey == null) {
            return null;
        }
        if(secretKey.length() != 16) {
            return null;
        }
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] raw = secretKey.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        IvParameterSpec iv = new IvParameterSpec(vector.getBytes());// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(encData.getBytes("utf-8"));
        return BASE64Encoder.encode(encrypted);// 此处使用BASE64做转码。
    }


    // 加密
    public String encrypt(String sSrc) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] raw = sKey.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
        return BASE64Encoder.encode(encrypted);// 此处使用BASE64做转码。
    }

    // 解密
    public String decrypt(String sSrc) throws Exception {
        try {
            byte[] raw = sKey.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 =BASE64Decoder.decodeToBytes(sSrc);// 先用base64解密
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, "utf-8");
            return originalString;
        } catch (Exception ex) {
        	Log.e("AESOperator",ex.toString());
            return null;
        }
    }
    public static String getAESkey(int length){
 
    	 StringBuffer buffer = new StringBuffer("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
    	 StringBuffer sb = new StringBuffer();
    	 Random r = new Random();
    	 int range = buffer.length(); 
    	 for (int i = 0; i < length; i ++) { 
    	sb.append(buffer.charAt(r.nextInt(range)));
    	}
    	 return sb.toString(); 
    	}
    public String decrypt(String sSrc, String key, String ivs) throws Exception {
        try {
            byte[] raw = key.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivs.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = BASE64Decoder.decodeToBytes(sSrc);// 先用base64解密
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, "utf-8");
            return originalString;
        } catch (Exception ex) {
            return null;
        }
    }
    
    public String encodeBytes(byte[] bytes) {
        StringBuffer strBuf = new StringBuffer();

        for (int i = 0; i < bytes.length; i++) {
            strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
            strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
        }

        return strBuf.toString();
    }

    public static void main(String[] args) throws Exception {
        // 需要加密的字串
        String cSrc = "{\"userid\":\"87\",\"tablename\":\"doctor\"}";
        
         System.out.println(getAESkey(16));
     
        AESOperator myAESO=new AESOperator();
       // myAESO.sKey="7481LC7rWfeW05If";
//        7481LC7rWfeW05If
//        Sp1lq7SCg7g7ZhVw
       // myAESO.ivParameter="Sp1lq7SCg7g7ZhVw";
        // 加密
        long lStart = System.currentTimeMillis();
        
        //String enString = myAESO.encrypt("["+JsonPluginsUtil.beanToJson(doctor)+"]");
        
        String enString = myAESO.encrypt(cSrc);
        System.out.println("加密后的字串是：" + enString);

        long lUseTime = System.currentTimeMillis() - lStart;
        System.out.println("加密耗时：" + lUseTime + "毫秒");
        // 解密
        lStart = System.currentTimeMillis();
        String DeString = myAESO.decrypt("b4J2nQ8Efar4tMvnbY++EHGbu6UdJaFmJjcpbQwurPdAZLeJxN0chmFnyiYF14n+DC7e04IcKUFC\nbxRV1kKJBd7QrkU3HLbFWXVWVjEdillYKaVteYYGN7G4tDn/4QC7l6lwxJa6Igsmz2SX957DC3me\ncXmg75rEB0qZ/v09P+i2BUaNWTsOCawVMGvGH3Jp6N/DihdJrnhra8lhMAe3c/0LPy5HCKt5h6eq\n0oKPDkaMQy6F8fAJizFrWTURtHJ61h0eadL4LxeeAdpx3W0orrOKhSWqXrLXAozEpKhUK6L8MF9F\ndqPgQT0/ftMFtwSn8m66CZO3C31lG/uN1kVRwAO5AlAYdSLziLfd3P9dmWgZGXYNJdskvGTnSnnn\nAhL6KJmrwdUs219Xn+fCz95VSOMAc0JXuWLGU6hAuy7nzlDpZkRRI2oIb+qLnljaKKkC26nMMwOJ\noo0/ZYRz1YhQnMIOZxixEgciE/soGroear66vWbCJwvDYlcdyov3SIzZmu4np/6HaEjPLTU8Br/C\nrnB8OHmJOJCFj0ZXkTNcO8dbXGMahsB1+O8rXlBxpburoyNDTOxSwIepoZR0CB+aFwyppkYcWrdQ\nrD7/t2/01bEo325VOYN/We8t7Yx9CwwjMsCXBQrroWj+35ZrZIUZp5kVV9bqXV8pr7675Nasq1ro\nsZoYQ8fKuX7Kjvbjv6et4CDoa8mTJByF1mciLeglHQUSnOffi8ihvNOJxX5bP2ucdg7By53OHL1t\n/qdKZKsAR8pypDhh6eSS5q5O05d6nbtiz1+ZlqBLAwlxKHWYXw27d89vZg4xoKp+jzRJcNY0EhVt\nbygQUarCEw8jm8HgVgH7Gk6LMFxLfSVHk8uic++QCi75prdgTreHCMn/yKdHOUW7FFiHKodlruM3\njloeHXNxAlH8XVq7d5WMjQ3ChGj4yflT+UQUUDhdqLpmAO65VsK+Ra0BELKMB2oouggARTmy0IbT\nOB3r8L0x+JFtrUOtCmyJppH33oYwa7eCI25m29a3Ytsgafp8yrYMm8xDMmWcjCOFiBzL3+88IL05\n8BLDGIAgphLjhN2PHsxLkEcsoEMyQsmVgweujeGMmszmfelTX8yX6MP01U3F9fXLw78Sb/ygVDmC\nB7jiUONSimlrREiUDEuvU7X5wIUzoN2bfJ2EX+hsu4lMK6xSyCjyTmSTGOaF8yqEhIDzVO+91mHA\nF5ePcex+xlkIhbBb5G2mTV5DlcQurIsvVpUenKog1/Th1T9AWgKnzTGIxUPIwFVegSuH3hBDrN1f\nkbLth9t2zbB5m3sl0EWI3XhBSvJXin3hXkP318R5fqm3x+Wr0aOU9MqwFV0emzjw+tny1ZwdOA==");
        System.out.println("解密后的字串是：" + DeString);
        lUseTime = System.currentTimeMillis() - lStart;
        System.out.println("解密耗时：" + lUseTime + "毫秒");
    }
}
